package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.yxt.common.sys.CommConstant;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;
import com.yxt.exception.XmlParserException;
import com.yxt.model.Favirote;
import com.yxt.service.FavoriteService;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.Window;  
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class RainStationDetailActivity extends Activity {
	private ImageView imgWaterMap;
	private ImageView imgWaterChart;
	private ImageView imgWaterFavorite;
	private Map<String,String> station = new HashMap<String,String>();
	private Map<String,String> rainmap = new HashMap<String,String>();
	private ProgressDialog dialog;
	
	private void downloadRainStation() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new RainDetailHandler());
		} catch (IOException e) {
			dialog.cancel();
			throw new InternetException("");
		} catch (ParserConfigurationException e){
			dialog.cancel();
			throw new XmlParserException("");
		} catch(SAXException ex) {
			dialog.cancel();
			throw new XmlParserException("");
		}	
	}

	private InputStream getInputStream() throws IOException{
		Intent intent = getIntent();
		String server =CommConstant.Sever.RAIN_SERVER;
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION +"raindetail.xml");
		} else {
			URL url = new URL(server + "rain/StaDetail.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE+"&stacode="+intent.getStringExtra("code"));
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}

	private class RainDetailHandler extends DefaultHandler {
		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("sta".equals(localName)) {
				for (int i = 0; i < attrs.getLength(); i++) {
					station.put(attrs.getLocalName(i), attrs.getValue(i));
				}
			} else if ("info".equals(localName)) {
				rainmap.put(attrs.getValue("label"), attrs.getValue("value"));
			} else if ("message".equals(localName)) {
				dialog.cancel();
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}
	}
	private void initComponent(){
		dialog = new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("数据下载中,请稍候...");
		dialog.show();
		final Handler hanlder = new Handler(){
			// 处理来自线程的消息,并将线程中的数据设置入listview
			public void handleMessage(Message msg)	{
				if (msg.what == 1)	{
					TextView lblStationName = (TextView)findViewById(R.id.lblStationName);
					lblStationName.setText(rainmap.get(getString(R.string.location_name)));
					TextView lblStationCode = (TextView)findViewById(R.id.lblStationCode);
					lblStationCode.setText(rainmap.get(getString(R.string.locaiton_code)));
					TextView lblStationTime = (TextView)findViewById(R.id.lblStationTime);
					lblStationTime.setText(rainmap.get(getString(R.string.location_endtime)));
					TextView lbl1 = (TextView)findViewById(R.id.lbl1);
					lbl1.setText(rainmap.get(getString(R.string.location_one)));
					TextView lbl2 = (TextView)findViewById(R.id.lbl2);
					lbl2.setText(rainmap.get(getString(R.string.location_three)));
					TextView lbl3 = (TextView)findViewById(R.id.lbl3);
					lbl3.setText(rainmap.get(getString(R.string.location_six)));
					TextView lbl4 = (TextView)findViewById(R.id.lbl4);
					lbl4.setText(rainmap.get(getString(R.string.location_twentyfour)));
					TextView lblStationAddr = (TextView)findViewById(R.id.lblStationAddr);
					lblStationAddr.setText(rainmap.get(getString(R.string.location_addr)));
					TextView lblStationLy = (TextView)findViewById(R.id.lblStationLy);
					lblStationLy.setText(rainmap.get(getString(R.string.location_ly)));
					TextView lblStationRiver = (TextView)findViewById(R.id.lblStationRiver);
					lblStationRiver.setText(rainmap.get(getString(R.string.location_river)));

					TextView lblStationJd = (TextView)findViewById(R.id.lblStationJd);
					lblStationJd.setText(rainmap.get(getString(R.string.location_jd)));
					TextView lblStationWd = (TextView)findViewById(R.id.lblStationWd);
					lblStationWd.setText(rainmap.get(getString(R.string.location_wd)));
					dialog.cancel();
				}
			}
		};
		
		new Thread(){
			public void run(){
				Looper.prepare();
				downloadRainStation();
				Message m = new Message();
				m.what = 1;
				hanlder.sendMessage(m);	// 给handle发送的消息
				Looper.loop();
			};

		}.start();
	}
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
		setContentView(R.layout.rain_detail);   //软件activity的布局
		ActivityStackControlUtil.add(this);	

		Button btnBackHome = (Button)findViewById(R.id.btnBackHome);
		btnBackHome.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(RainStationDetailActivity.this, MainActivity.class);
				startActivity(intent);
			}
		});
		imgWaterMap = (ImageView)findViewById(R.id.imgWaterMap);
		imgWaterChart = (ImageView)findViewById(R.id.imgWaterChart);
		imgWaterFavorite = (ImageView)findViewById(R.id.imgWaterFavorite);

		imgWaterMap.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(RainStationDetailActivity.this, RainStationMapActivity.class);
				intent.putExtra("code", rainmap.get(getString(R.string.locaiton_code)));
				intent.putExtra("name", rainmap.get(getString(R.string.location_name)));
				intent.putExtra("jd", rainmap.get(getString(R.string.location_jd)));
				intent.putExtra("wd", rainmap.get(getString(R.string.location_wd)));
				startActivity(intent);
			}
			
		});
		imgWaterChart.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(RainStationDetailActivity.this, RainStationWeekChartActivity.class);
				intent.putExtra("code", rainmap.get(getString(R.string.locaiton_code)));
				intent.putExtra("name", rainmap.get(getString(R.string.location_name)));
				intent.putExtra("type", CommConstant.Rain.CHART_TYPE_HOUR);
				startActivity(intent);
			}
			
		});
		imgWaterFavorite.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				AlertDialog.Builder builder = new AlertDialog.Builder(RainStationDetailActivity.this); 
				builder.setMessage("是否确定要收藏此测站？").setCancelable(false)        
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {            
					public void onClick(DialogInterface dialog, int id) {   
						FavoriteService service = new FavoriteService(RainStationDetailActivity.this);
						Favirote favirote = new Favirote();
						favirote.setCode(rainmap.get(getString(R.string.locaiton_code)));
						favirote.setName(rainmap.get(getString(R.string.location_name)));
						favirote.setType(String.valueOf(CommConstant.Station.RAIN_LOCATION));
						favirote.setAddr(rainmap.get(getString(R.string.location_addr)));
						favirote.setRiver(rainmap.get(getString(R.string.location_river)));
						service.saveOrUpdateFavirote(favirote);
						service.closeDB();
						Toast.makeText(RainStationDetailActivity.this, "测站收藏成功", Toast.LENGTH_LONG).show();
					}        
				}).setNegativeButton("取消", new DialogInterface.OnClickListener() {            
					public void onClick(DialogInterface dialog, int id) {                 
						dialog.cancel();            
					}        
				}).show();
			}
			
		});
		initComponent();		
	}
	
	protected void onDestroy() {     
        super.onDestroy();
        ActivityStackControlUtil.remove(this);
	}
}